/**
 * Summary: 异步回调页面JS函数管理对象
 * Version 1.0
 * Date: 13-11-26
 * Time: 下午7:55
 * Copyright: Copyright (c) 2013
 */

package cn.pedant.SafeWebViewBridge;

import ohos.agp.components.webengine.WebView;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.lang.ref.WeakReference;

public class JsCallback {
    private static final String CALLBACK_JS_FORMAT = "javascript:%s.callback(%d, %d %s);";
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0x00020,"JsCallBack");
    private final int mIndex;
    private boolean isCouldGoOn;
    private final WeakReference<WebView> mWebViewRef;
    private int isPermanent;
    private final String mInjectedName;

    /**
     * 构造
     *
     * @param view 浏览器
     * @param injectedName 类名
     * @param index 位置
     */
    public JsCallback(WebView view, String injectedName, int index) {
        isCouldGoOn = true;
        mWebViewRef = new WeakReference<WebView>(view);
        mInjectedName = injectedName;
        mIndex = index;
    }

    /**
     * apply
     *
     * @param args 对象列表
     * @throws JsCallbackException 异常
     */
    public void apply(Object... args) throws JsCallbackException {
        if (mWebViewRef.get() == null) {
            throw new JsCallbackException("the WebView related to the JsCallback has been recycled");
        }
        if (!isCouldGoOn) {
            throw new JsCallbackException("the JsCallback isn't permanent,cannot be called more than once");
        }
        StringBuilder sb = new StringBuilder();
        for (Object arg : args) {
            sb.append(",");
            boolean isStrArg = arg instanceof String;
            if (isStrArg) {
                sb.append("\"");
            }
            sb.append(arg);
            if (isStrArg) {
                sb.append("\"");
            }
        }
        String execJs = String.format(CALLBACK_JS_FORMAT, mInjectedName, mIndex, isPermanent, sb.toString());
        HiLog.info(TAG, execJs);
        mWebViewRef.get().load(execJs);
        isCouldGoOn = isPermanent > 0;
    }

    public void setPermanent(boolean isValue) {
        isPermanent = isValue ? 1 : 0;
    }

    public static class JsCallbackException extends Exception {
        /**
         * 自定义异常
         *
         * @param msg 异常信息
         */
        public JsCallbackException(String msg) {
            super(msg);
        }
    }
}
